<?php

namespace app\common\service;

use think\Collection;
use think\facade\Db;

class MenuService
{
    /**
     * 登录者id
     * @var integer
     */
    protected int $uid;

    protected string $appName;

    protected int $appId;

    public function __construct($uid, $app_name, $appId)
    {
        $this->uid     = $uid;
        $this->appName = $app_name;
        $this->appId   = $appId;
        return $this;
    }


    /**
     * 获取后台菜单树信息
     */
    public function getMenuTree($show = false): array
    {
        /** @var AuthService $authService */
        $authServer = app(AuthService::class, ['uid' => $this->uid, 'app_name' => $this->appName]);
        return $this->buildMenuChild(0, $this->getMenuData($show), $authServer);
    }

    /**
     * 获取所有菜单数据
     */
    protected function getMenuData($show): array
    {
        $appName = $this->appName == 'admin' ? 'group' : $this->appName;
        $sql     = Db::name($appName . '_menu')
                     ->field('id,pid,title,icon,href,api,menu_type,target,file_path,redirect,status,is_show')
                     ->where("delete_time is null")
                     ->where($appName . '_id', $this->appId);
        //        if (!$show) $sql = $sql->where(['status' => 1, 'is_show' => 1]);
        if (!$show) $sql = $sql->where(['status' => 1]);
        return $sql->order([
                                   'sort' => 'desc',
                                   'id'   => 'asc',
                           ])
                   ->select()->toArray();
    }

    private function buildMenuChild($pid, $menuList, AuthService $authServer): array
    {
        $treeList = [];
        foreach ($menuList as &$v) {
            $check = empty($v['href']) || $authServer->checkAuth($v['id'], $v['href']);
            if ($pid == $v['pid'] && $check) {
                $node  = $v;
                $child = $this->buildMenuChild($v['id'], $menuList, $authServer);
                if (!empty($child)) {
                    $node['children'] = $child;
                }
                if (!empty($v['href']) || !empty($child)) {
                    $treeList[] = $node;
                }
            }
        }
        return $treeList;
    }


}